<template>
  <div id="KnowledgeApprovalList">
    <div class="bodyContent">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-form :data="dataform">
            <vxe-form-item title="计划结束时间[止]">
              <template #default>
                <el-date-picker v-model="timeDater" type="daterange" :value-format="'YYYY-MM-DD'" range-separator="To" start-placeholder="Start date" end-placeholder="End date" @change="datePickerChange" clearable @clear="handleClear" style="margin-right: 10px" />
              </template>
            </vxe-form-item>
            <vxe-form-item title="快速查询" field="searchValue">
              <template #default="{ data }">
                <vxe-input style="width: 180px; margin-right: 10px" v-model="data.searchValue" type="search" clearable class="vxeInputSearch" placeholder="设备名称" @keyup="findPatrolPlanList" @search-click="findPatrolPlanList"></vxe-input>
              </template>
            </vxe-form-item>
            <vxe-form-item title="计划巡检人" field="handler">
              <VxePulldownSelection
                ref="employeeSelectRef"
                :url="'/api/sys/hisEmployee/finAllHisEmployeeList'"
                @confirmClick="SelectRowClick1"
                :tableColumn="[
                  { title: '编号', field: 'code' },
                  { title: '名称', field: 'name' }
                ]"
                :aimKeys="[
                  { formKey: 'code', rowKey: 'code' },
                  { formKey: 'name', rowKey: 'name' }
                ]"
                :displayTexts="['name']"
                :displayTextObj="dataform.handler"
              />
            </vxe-form-item>
            <vxe-form-item>
              <vxe-button style="margin-left: 10px" type="text" status="success" class="button-blue" icon="vxe-icon-search" content="查询" @click="findPatrolPlanList"></vxe-button>
            </vxe-form-item>
          </vxe-form>
        </template>
      </vxe-toolbar>
      <div id="ecList1" class="chart"></div>
      <div style="height: calc(100% - 290px)">
        <vxe-table ref="patrolPlanTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="patrolPlanList" :loading="tloading" @current-change="patrolTaskRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
          <vxe-column type="seq" width="30" title=""></vxe-column>
          <vxe-column field="code" title="计划编号"> </vxe-column>
          <vxe-column field="name" title="计划名称"></vxe-column>
          <vxe-column field="beginTime" title="开始时间" :formatter="formatOperateTime"> </vxe-column>
          <vxe-column field="endTime" title="结束时间" :formatter="formatOperateTime"> </vxe-column>
          <vxe-column field="shouldPatrol" title="应检次数"> </vxe-column>
          <vxe-column field="rightPatrol" title="实检次数"> </vxe-column>
          <vxe-column field="noPatrol" title="未检次数"> </vxe-column>
          <vxe-column field="shouldInspected" title="应检设备台次"> </vxe-column>
          <vxe-column field="realityInspected" title="实检设备台次"> </vxe-column>
          <vxe-column field="noPassCount" title="未检设备台次"> </vxe-column>
        </vxe-table>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { onMounted, getCurrentInstance, reactive, ref } from 'vue';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
let { proxy }: any = getCurrentInstance();
import * as echarts from 'echarts';
import { formatDateTime, IsEmpty } from '@/utils/common';
import { log } from 'console';

// 查询表单数据
let dataform = reactive({
  beginTime: '',
  endTime: '',
  searchValue: '',
  handler: ''
});

let timeDater = ref('');

let patrolPlanList: any = reactive([]);
let dateList: any = reactive([]);
let yjList: any = reactive([]);
let sjList: any = reactive([]);
let wjList: any = reactive([]);
let tloading = ref(false); //加载状态

const shortcuts = [
  {
    text: '今天',
    value: new Date()
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 1);
      return date;
    }
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 7);
      return date;
    }
  }
];

onMounted(() => {
  findPatrolPlanList(); // 获取质控规则表格数据
});

function patrolTaskRowClick({ row }: any) {
  if (!IsEmpty(row)) {
    (proxy.$refs.patrolPlanTableRef as any).setCurrentRow(row);
    getChartdata(row.id);
  }
}

// 点击组件表格行(被通知人)
function SelectRowClick1(row) {
  dataform.handler = row.row.code;
}
// 格式化日期时间
function formatOperateTime({ cellValue, row, column }) {
  // 假设cellValue是一个时间戳，你可以使用Date对象将其格式化为包含毫秒的形式
  const date = new Date(cellValue);
  return formatDateTime(date, 'yyyy-MM-dd'); // 这会返回包含毫秒的 ISO 8601 格式的时间字符串
}
function findPatrolPlanList() {
  tloading.value = true;
  patrolPlanList.length = 0; //放入数据前清空数据
  const url = '/api/eq/patrolPlan/findPatrolList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: dataform.searchValue,
        beginTime: dataform.beginTime,
        endTime: dataform.endTime,
        handler: dataform.handler
      }
    })
    .then((res: any) => {
      patrolPlanList.push(...res.data);
      patrolTaskRowClick({ row: patrolPlanList[0] }); //默认选中第一条数据
      if (patrolPlanList.length>0){
        getChartdata(patrolPlanList[0].id);
      }else {
        dateList.length = 0;
        yjList.length = 0;
        sjList.length = 0;
        wjList.length = 0;
        setChartData();
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}
function getChartdata(planId: any) {
  dateList.length = 0;
  yjList.length = 0;
  sjList.length = 0;
  wjList.length = 0;
  const url = '/api/eq/patrolTask/patrolTaskAnalysis';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { planId: planId } })
    .then((res: any) => {
      dateList.push(...res.data.date);
      yjList.push(...res.data.yjList);
      sjList.push(...res.data.sjList);
      wjList.push(...res.data.wjList);
      setChartData();
    })
    .catch((err: any) => {
      console.log(err)
    });
}
function setChartData() {
  if (echarts.getInstanceByDom(document.getElementById('ecList1') as HTMLElement)) {
    echarts.dispose(document.getElementById('ecList1') as HTMLElement);
  }
  const myChart = echarts.init(document.getElementById('ecList1') as HTMLElement);
  const uniqueDateList = [...new Set(dateList)];
  const yj = [...new Set(yjList)];
  const sj = [...new Set(sjList)];
  const wj = [...new Set(wjList)];

  myChart.setOption({
    title: {
      text: '计划执行趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['应检次数', '实检次数', '未检次数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      data: uniqueDateList
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '应检次数',
        type: 'line',
        data: yj
      },
      {
        name: '实检次数',
        type: 'line',
        data: sj
      },
      {
        name: '未检次数',
        type: 'line',
        data: wj
      }
    ]
  });
}

function datePickerChange(e) {
  if (timeDater.value) {
    dataform.beginTime = timeDater.value[0];
    dataform.endTime = timeDater.value[1];
  } else {
    dataform.beginTime = '';
    dataform.endTime = '';
  }
}
</script>

<style lang="scss" scoped>
#KnowledgeApprovalList {
  height: 100%;
  .bodyContent {
    height: calc(100% - 20px);
    background-color: #fff;
    .chart {
      width: 100%;
      height: 250px;
    }
  }
}
</style>
